<template>
  <div class="video-upload-container">
    <el-form 
      ref="uploadFormRef" 
      :model="uploadForm" 
      :rules="uploadRules" 
      label-width="120px" 
      status-icon>
      <el-form-item label="上传视频" prop="url" required>
        <el-upload class="video-adder" :limit="1"  v-if="!videoPreview"
          drag
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleVideoChange"
          :on-remove="handleVideoRemove"
          accept="video/*">
          <div class="upload-icon">
            <svg-icon icon-class="upload"/>
          </div>
          <div class="el-upload__text">
            将视频拖到此处，或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持MP4格式，且文件大小不超过500MB
            </div>
          </template>
        </el-upload>
        
        <div class="video-preview-container" v-if="videoPreview">
          <video :src="videoPreview" controls class="video-preview"></video>
          <svg-icon icon-class="trash" class="delete-icon" @click="handleVideoRemove" title="删除视频"></svg-icon>
        </div>
      </el-form-item>

      <el-form-item label="视频封面" prop="cover">
        <el-upload :limit="1" v-if="!coverPreview"
          class="cover-uploader"
          drag
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleCoverChange"
          :on-remove="handleCoverRemove"
          accept="image/*">
          <div class="upload-icon">
            <svg-icon icon-class="upload"/>
          </div>
          <div class="el-upload__text">
            将封面拖到此处，或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持JPG/PNG格式，且文件大小不超过10MB
            </div>
          </template>
        </el-upload>
        <div class="video-preview-container" v-if="coverPreview">
          <img :src="coverPreview" class="cover-preview"/>
          <svg-icon icon-class="trash" class="delete-icon" @click="handleCoverRemove" title="删除封面"></svg-icon>
        </div>        
      </el-form-item>

      <el-form-item label="作品标题" prop="name" required>
        <el-input 
          v-model="uploadForm.name" 
          placeholder="请输入作品标题" 
          maxlength="50" 
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="作品分类" prop="programTypeId" required>
        <el-select v-model="uploadForm.programTypeId" 
          placeholder="请选择作品分类" style="width: 100%;">
          <el-option 
            v-for="item in programTypeList" 
            :key="item.id" 
            :label="item.name" 
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="作品标签" prop="tag">
        <el-input-tag
          v-model="uploadForm.tag"
          tag-type="danger"
          tag-effect="plain"
          placeholder="输入标签，回车添加">
          <template #tag="{ value }">
            <div class="flex items-center">
              <span>{{ value }}</span>
            </div>
          </template>
        </el-input-tag>
      </el-form-item>

      <el-form-item label="作品简介" prop="remark">
        <el-input 
          v-model="uploadForm.remark" 
          type="textarea" 
          :rows="4" 
          placeholder="请输入作品简介" 
          maxlength="500" 
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="授权方式" prop="authType" required>
        <el-select 
          v-model="uploadForm.authType" 
          placeholder="请选择授权方式"
          style="width: 100%;">
          <el-option 
            v-for="item in authTypeOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="uploadForm.agreement">
          我已阅读并同意遵守 
          <el-link type="danger" href="/creator-agreement" target="_blank" style="vertical-align: top;">
            创作者协议
          </el-link>
        </el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button class="red-btn" @click="submitUpload" :disabled="!isFormValid" round  size="large">
          立即发布
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { programType, upload, addMyVideos } from "@/api/pcApi";
import { ElMessage } from 'element-plus';

// 定义表单数据和验证规则
const uploadFormRef = ref(null)
const videoPreview = ref(null)
const coverPreview = ref(null)

const programTypeList = ref([])
const getProgramTypeList = () =>{
  programType().then(res => {
    programTypeList.value = res
  }).catch(err => {
    console.log(err)
  })
}

const uploadForm = reactive({
  url: '',
  cover: '',
  name: '',
  authType: '',
  remark: '',
  agreement: false,
	// url: 'https://miaocode-ai.oss-ap-southeast-1.aliyuncs.com/test/2025-01-13/6784d596e4b01764fb0c3de3.mp4',
	// cover: 'https://www.bing.com/th?id=OHR.GreatWallStairs_ROW7047345200_1920x1080.webp&qlt=50',
	// name: '我在时光里兜售幸福',
	// authType: '',
	// remark: '',
	// agreement: false
})

// 授权方式选项
const authTypeOptions = [
  { value: 0, label: '不采用共享协议' },
  { value: 1, label: '署名-非商业性使用-禁止演绎' },
  { value: 2, label: '署名-非商业性使用-相同方式共享' },
  { value: 3, label: '署名-禁止演绎' },
  { value: 4, label: '署名-相同方式共享' }
]

// 表单验证规则
const uploadRules = {
  url: [
    { 
      required: true, 
      message: '请上传视频', 
      trigger: 'change' 
    }
  ],
  name: [
    { 
      required: true, 
      message: '请输入作品标题', 
      trigger: 'blur' 
    }
  ],
  authType: [
    { 
      required: true, 
      message: '请选择授权方式', 
      trigger: 'change' 
    }
  ],
  remark: [
    { 
      required: true, 
      message: '请输入作品简介', 
      trigger: 'blur' 
    }
  ],
  // agreement: [
  //   { 
  //     validator: (rule, value, callback) => {
  //       if (!value) {
  //         callback(new Error('请同意创作者协议'))
  //       } else {
  //         callback()
  //       }
  //     }, 
  //     trigger: 'change' 
  //   }
  // ]
}

const getFileUrl = (formData, type) => {
  return upload(formData).then(res => {
    if (type === 'cover') {
      uploadForm.cover = res
    } else if (type === 'video') {
      uploadForm.url = res
    }
    return res
  }).catch(err => {
    ElMessage.error(err.message)
  })
};

// 视频文件处理
const handleVideoChange = (uploadFile) => {
  uploadForm.name = uploadFile.name
  videoPreview.value = URL.createObjectURL(uploadFile.raw)  
  const formData = new FormData();
  formData.append('file', uploadFile.raw);
  getFileUrl(formData, 'video')
}

const handleVideoRemove = () => {
  uploadForm.url = null
  videoPreview.value = null
}

// 封面文件处理
const handleCoverChange = (uploadFile) => {
  coverPreview.value = URL.createObjectURL(uploadFile.raw)
  // 创建FormData用于上传
  const formData = new FormData();
  formData.append('file', uploadFile.raw);
  getFileUrl(formData, 'cover');
}

const handleCoverRemove = () => {
  uploadForm.cover = null
  coverPreview.value = null
}

// 表单验证状态
const isFormValid = computed(() => {
  return uploadForm.url &&
         uploadForm.name.trim() !== '' && 
         uploadForm.authType !== '' && 
         uploadForm.remark.trim() !== '' && 
         uploadForm.agreement
})

// 提交表单
const submitUpload = () => {
  if (!uploadForm.agreement) {
    ElMessage.error('请同意创作者协议')
    return false
  }
  uploadFormRef.value.validate((valid) => {
    if (valid) {
      delete uploadForm.agreement
      uploadForm.tag = uploadForm.tag.toString()
      console.log(uploadForm)
      return addMyVideos(uploadForm).then(res => {
        console.log(res)
        uploadFormRef.value.resetFields()
      }).catch(err => {
        console.log(err)
      })
    } else {
      ElMessage.error('请检查表单并完成所有必填项')
      return false
    }
  })
}

onMounted(() => {
  getProgramTypeList()
})
</script>

<style lang="less" scoped>
.video-upload-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  margin-bottom: 180px;
  .video-preview-container {
    position: relative;
    .delete-icon {
      position: absolute;
      font-size: 18px;
      top: 10px;
      right: 10px;
      cursor: pointer;
      color: #F56C6C;
    }
  }

  .video-preview, .cover-preview {
    max-width: 390px;
    margin-left: 16px;
    border-radius: 10px;
  }

  .el-upload {
    width: 100%;
  }

  .el-upload-dragger {
    width: 100%;
  }

  .upload-icon {
    font-size: 40px;
    color: #8c939d;
    text-align: center;
    margin-bottom: 10px;
  }

  .red-btn {
    background: #A30000;
    color: #fff;
    border: 0;
    border-radius: 50px;
    padding-top: 12px;
    padding-bottom: 12px;
    &:hover {
      background: #B30000;
      color: #fff;
    }    
  }
}
</style>
